<template>
    <div>
      <el-form v-if="searchState" size="small" :inline="true" class="query-form" ref="searchForm" :model="searchForm" @keyup.enter.native="refreshList()" @submit.native.prevent>
         <el-form-item label="年" prop="createdate">
           <el-input-number v-model="createdate" controls-position="right" :min="2021" :max="9999"></el-input-number>
         </el-form-item>
         <el-form-item label="投票次数" prop="ticketCount">
           <el-input-number v-model="ticketCount" controls-position="right" :min="1" :max="9999"></el-input-number>
         </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="refreshList()" size="small">查询</el-button>
            <el-button @click="resetSearch()" size="small">重置</el-button>
          </el-form-item>
      </el-form>
      <div class="bg-white top">
        <div align="center" style="font-size: 26px;">{{new Date().getFullYear() + '年度中层干部考核民主谈话表'}}</div>
        <br>
      <el-row>
      </el-row>
    <el-table
      :data="dataList"
       size="small"
       style="border: 2px solid #76838F"
      :header-cell-style="headerCellStyle"
      :cell-style="cellStyle"
      @sort-change="sortChangeHandle"
      v-loading="loading"
      class="table">
    <el-table-column
      label="序号"
      width="100px"
      align="center"
      type="index">
      </el-table-column>
    <el-table-column
        prop="name"
        align="center"
        label="姓名">
      </el-table-column>
    <el-table-column
        prop="currentPosition"
        min-width="200px"
        align="left"
        header-align="center"
        class="cell"
        label="现任职务">
      </el-table-column>
    <el-table-column
        align="center"
        show-overflow-tooltip
        label="总体评价">
        <el-table-column
            prop="remarks"
            align="center"
            show-overflow-tooltip
            label="优秀">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.youxiu" style="width: 100px;" controls-position="right" :min="0" :max="9999"></el-input-number>
            </template>
          </el-table-column>
        <el-table-column
            prop="remarks"
            align="center"
            show-overflow-tooltip
            label="称职">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.chenzhi" style="width: 100px;" controls-position="right" :min="0" :max="9999"></el-input-number>
            </template>
          </el-table-column>
        <el-table-column
            prop="remarks"
            align="center"
            show-overflow-tooltip
            label="基本称职">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.jibenchenzhi" style="width: 100px;" controls-position="right" :min="0" :max="9999"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
              prop="remarks"
              align="center"
              show-overflow-tooltip
              label="不称职">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.buchenzhi" style="width: 100px;" controls-position="right" :min="0" :max="9999"></el-input-number>
              </template>
            </el-table-column>
      </el-table-column>
    </el-table>
    <br>
    <div align="center" style="font-size: 26px;">{{pageNo + '/' + total + '页'}}</div>
    <br>
    <el-row style="margin-left: 45%;">
      <el-button class="button1" v-show="pageNo !== 1" type="primary" size="big" @click="pageCount('pre')">上一页</el-button>
      <el-button class="button2" v-show="pageNo !== total" type="primary" size="big" @click="pageCount('next')">下一页</el-button>
      <el-button v-show="pageNo === total && subState" type="primary" size="big" @click="submit()">提交</el-button>
    </el-row>
    </div>
    <asyn-for-tool ref='asynForTool' @returnData='returnData(arguments)'></asyn-for-tool>
  </div>
</template>

<script>
  import {clearLoginInfo} from '@/utils'
  export default {
    data () {
      return {
        searchForm: {
          name: '',
          currentPosition: '',
          remarks: '',
          ticketCount: ''
        },
        createdate: new Date().getFullYear(),
        ticketCount: 1,
        state: false,
        loadings: '',
        submitNumber: 0,
        finishNumber: 0,
        subState: false,
        dataList: [],
        dataLists: [],
        dataArr: [],
        errList: '', // 未填写单位
        pageNo: 1,
        pageSize: 5000,
        total: 0,
        orderBy: '',
        dataListSelections: [],
        isImportCollapse: false,
        loading: false,
        redisCount: 0 // redis存储计数
      }
    },
    components: {
      // SchoolleaderMiddlecadresForm
    },
    computed: {
      searchState () {
        return localStorage.getItem('loginName') === 'admin'
      }
    },
    watch: {
      'dataLists': {
        handler (newVal, oldVal) {
            this.redisCount++
            if (this.redisCount >= 3) {
              this.$http({
                url: '/peopleinformation/administrativelevel/peopleAdministrativeLevel/Redisset',
                method: 'post',
                data: {
                  key: (localStorage.getItem('loginName') + this.$route.path),
                  value: JSON.stringify(newVal)
                }
              })
              this.redisCount = 0
            }
        },
        deep: true
      }
    },
    activated () {
      this.refreshList()
    },
    methods: {
      cellStyle ({row, column, rowIndex, columnIndex}) {
        if (this.state) {
          if (row.remarks === "" || row.remarks === undefined) {
            return "background:#d3d3d3;border:2px;color: #FFFFFF;font-size: 20px;border: 1px solid black;"
          }
        }
        return "font-size: 20px;border: 1px solid black;"
      },
      headerCellStyle ({row}) {
        return "font-size: 24px;border: 1px solid black;font-weight:bold;"
      },
      // 提交成功
      submitSuccess () {
        this.$http({
          url: '/peopleinformation/administrativelevel/peopleAdministrativeLevel/Redisset',
          method: 'post',
          data: {
            key: (localStorage.getItem('loginName') + 'state'),
            value: '已填写'
          }
        })
        localStorage.removeItem('loginName')
      },
      jumpUp () {
        this.$router.push('/ticket/speakpeoplecrowd/SpeakPeopleCrowdList')
      },
      // 退出登录
      out () {
        this.$http({
          url: '/sys/logout',
          method: 'get'
        }).then(({data}) => {
          if (data && data.success) {
            clearLoginInfo()
            if (process.env.VUE_APP_SSO_LOGIN === 'true') {
              let service = window.location.protocol + '//' + window.location.host + '/'
              window.location.href = `${process.env.VUE_APP_CAS_SERVER}/logout?service=${service}`
              this.$tool.flash()
            } else {
              this.$router.replace({name: 'login'})
              this.$tool.flash()
            }
          }
        })
      },
      // 获取数据列表
      refreshList () {
        this.subState = false
        this.loading = true
        this.redisCount = 0
        this.dataLists = []
        this.dataList = []
        if (localStorage.getItem('loginName') === 'admin') {
          if (this.createdate === '' || this.createdate === null || this.createdate === undefined || this.ticketCount === undefined || this.ticketCount === undefined || this.ticketCount === undefined) {
            this.searchForm.ticketCount = new Date().getFullYear() + '-' + 1
          } else {
            this.searchForm.ticketCount = this.createdate + '-' + this.ticketCount
          }
          this.searchForm.admin = 'admin'
        } else {
          this.searchForm.ticketCount = localStorage.getItem('checkTime')
          this.searchForm.admin = ''
        }
        this.searchForm.key = localStorage.getItem('loginName') + this.$route.path
          this.$http({
            url: '/ticket/schleamiddlecadres/schoolleaderMiddlecadres/list',
            method: 'get',
            params: {
              'pageSize': 9999,
              ...this.searchForm
            }
          }).then(({data}) => {
            if (data && data.success) {
              this.pageNo = 1
              this.dataLists = data.page.list
              if (this.dataLists.length % 10 === 0) {
                this.total = Math.floor(this.dataLists.length / 10)
              } else {
                this.total = Math.floor(this.dataLists.length / 10) + 1
              }
              for (let m in this.dataLists) {
                this.$set(this.dataLists[m], 'youxiu', 0)
                this.$set(this.dataLists[m], 'chenzhi', 0)
                this.$set(this.dataLists[m], 'jibenchenzhi', 0)
                this.$set(this.dataLists[m], 'buchenzhi', 0)
              }
              this.dataList = this.dataLists.slice(0, 10)
              this.subState = true
              this.loading = false
            }
          })
      },
      // 当前页校验
      pageValidation () {
        this.errList = ''
        for (var i in this.dataList) {
          if (this.dataList[i].remarks === '' || this.dataList[i].remarks === undefined) {
            this.errList += " " + this.dataList[i].name
            break
          }
        }
      },
      // 页码
      pageCount (val) {
        var valPage = ''
        if (val === 'next') {
          this.pageValidation()
        }
        if (localStorage.getItem('loginName') !== 'admin') {
          if (this.errList !== '') {
            this.state = true
            var id = ''
            for (var k = 1; k < this.errList.length; k++) {
              if (this.errList.charAt(k) !== ' ') { // 不是空串
                id += this.errList.charAt(k)
              } else {
                break
              }
            }
            var loc = 0
            for (var j = 0; j < this.dataList.length; j++) {
              if (this.dataList[j].id === id) {
                loc = j // 转换成序号
                break
              }
            }
            window.scrollTo(0, 10 + 80 + 90.56 + loc * 58)
          } else {
            this.state = false
            if (val === 'next') {
              if (this.pageNo === this.total) {
                alert(`当前是最后一页`)
              } else {
                valPage = this.pageNo + 1
                this.currentChangeHandle(valPage)
              }
            } else {
              if (this.pageNo === 1) {
                alert(`当前是第一页`)
              } else {
                valPage = this.pageNo - 1
                this.currentChangeHandle(valPage)
              }
            }
          }
      } else {
        if (val === 'next') {
          if (this.pageNo === this.total) {
            alert(`当前是最后一页`)
          } else {
            valPage = this.pageNo + 1
            this.currentChangeHandle(valPage)
          }
        } else {
          if (this.pageNo === 1) {
            alert(`当前是第一页`)
          } else {
            valPage = this.pageNo - 1
            this.currentChangeHandle(valPage)
          }
        }
      }
      },
      // 提交数据
      submit () {
        this.errList = ''
        this.dataArr = []
          for (let l in this.dataLists) {
            this.$set(this.dataLists[l], 'tableName', 'schoolleader_middlecadres')
            for (let n = 0; n < this.dataLists[l].youxiu; n++) {
              this.dataLists[l].remarks = '优秀'
              this.dataArr.push(this.lodash.pick(this.dataLists[l], 'remarks', 'name', 'mark', 'tableName', 'identity', 'currentPosition', 'ticketCount'))
            }
            for (let o = 0; o < this.dataLists[l].chenzhi; o++) {
              this.dataLists[l].remarks = '称职'
              this.dataArr.push(this.lodash.pick(this.dataLists[l], 'remarks', 'name', 'mark', 'tableName', 'identity', 'currentPosition', 'ticketCount'))
            }
            for (let p = 0; p < this.dataLists[l].jibenchenzhi; p++) {
              this.dataLists[l].remarks = '基本称职'
              this.dataArr.push(this.lodash.pick(this.dataLists[l], 'remarks', 'name', 'mark', 'tableName', 'identity', 'currentPosition', 'ticketCount'))
            }
            for (let q = 0; q < this.dataLists[l].buchenzhi; q++) {
              this.dataLists[l].remarks = '不称职'
              this.dataArr.push(this.lodash.pick(this.dataLists[l], 'remarks', 'name', 'mark', 'tableName', 'identity', 'currentPosition', 'ticketCount'))
            }
          }
          this.loading = true
          this.subState = false
            this.$http({
              url: `/ticketdata/leadershipdata/leadershipData/manysave`,
              method: 'post',
              data: {
                account: localStorage.getItem('loginName'),
                finishState: '已完成',
                middlerleader: this.dataArr
              }
            })
            this.submitSuccess()
            this.out()
            this.loading = false
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageNo = 1
        this.refreshList()
      },
      // 当前页
      currentChangeHandle (val) {
        if (this.errList === '' || localStorage.getItem('loginName') === 'admin') {
          this.$http({
            url: '/peopleinformation/administrativelevel/peopleAdministrativeLevel/Redisset',
            method: 'post',
            data: {
              key: (localStorage.getItem('loginName') + this.$route.path),
              value: JSON.stringify(this.dataLists)
            }
          })
          this.pageNo = val
          this.dataList = []
          this.redisCount = 0
          this.dataList = this.dataLists.slice((val - 1) * 10, (val - 1) * 10 + 10)
        }
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
    // 排序
      sortChangeHandle (obj) {
        if (obj.order === 'ascending') {
          this.orderBy = obj.prop + ' asc'
        } else if (obj.order === 'descending') {
          this.orderBy = obj.prop + ' desc'
        } else {
          this.orderBy = ''
        }
        this.refreshList()
      },
      // 新增
      add () {
        this.$refs.schoolleaderMiddlecadresForm.init('add', '')
      },
      // 修改
      edit (id) {
        id = id || this.dataListSelections.map(item => {
          return item.id
        })[0]
        this.$refs.schoolleaderMiddlecadresForm.init('edit', id)
      },
      // 查看
      view (id) {
        this.$refs.schoolleaderMiddlecadresForm.init('view', id)
      },
      // 删除
      del (id) {
        let ids = id || this.dataListSelections.map(item => {
          return item.id
        }).join(',')
        this.$confirm(`确定删除所选项吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          this.$http({
            url: '/ticket/schleamiddlecadres/schoolleaderMiddlecadres/delete',
            method: 'delete',
            params: {'ids': ids}
          }).then(({data}) => {
            if (data && data.success) {
              this.$message.success(data.msg)
              this.refreshList()
            }
            this.loading = false
          })
        })
      },
      // 导入成功
      uploadSuccess (res, file) {
        if (res.success) {
          this.$message.success({dangerouslyUseHTMLString: true,
            message: res.msg})
        } else {
          this.$message.error(res.msg)
        }
      },
      // 下载模板
      downloadTpl () {
        this.$utils.download('/ticket/schleamiddlecadres/schoolleaderMiddlecadres/import/template')
      },
      exportExcel () {
        let params = {
          ...this.searchForm
        }
        this.$utils.download('/ticket/schleamiddlecadres/schoolleaderMiddlecadres/export', params)
      },
      resetSearch () {
        this.$refs.searchForm.resetFields()
        this.refreshList()
      }
    }
  }
</script>
<style type="text/css">
  .msgBox{
    width: auto !important;
  }
  .table .cell {
      white-space: pre-wrap;
  }
  .loadingStyle {
    font-size: 32px;
  }
</style>
